<?php
use  \Phalcon\Mvc\Model\Validator\Email;
use  \Phalcon\Mvc\Model\Validator\StringLength;

class User extends \Phalcon\Mvc\Model {

    /**
     *
     * @var integer
     */
    public $id;

    /**
     *
     * @var string
     */
    public $userName;

    /**
     *
     * @var string
     */
    public $emai;

    /**
     *
     * @var string
     */
    public $password;

    /**
     *
     * @var string
     */
    public $salt;

    /**
     *
     * @var integer
     */
    public $create_time;

    /**
     * Returns table name mapped in the model.
     *
     * @return string
     */
    public function getSource() {
        return 'user';
    }

    /**
     * Allows to query a set of records that match the specified conditions
     *
     * @param mixed $parameters
     * @return User[]
     */
    public static function find($parameters = null) {
        return parent::find($parameters);
    }

    /**
     * Allows to query the first record that match the specified conditions
     *
     * @param mixed $parameters
     * @return User
     */
    public static function findFirst($parameters = null) {
        return parent::findFirst($parameters);
    }

    //保存之前
    public function beforeSave() {
        //取得注入的类
        $common         = $this->getDI()->get('common');
        $this->salt     = $common->rand_string();//加盐
        $this->password = $common->md5_string($this->password, $this->salt); //加密加盐

    }

    //创建之前
    public function beforeCreate() {
        $this->create_time = time();
    }

    //更新之前 验证
    public function beforeUpdate() {
        $this->validate(new \Phalcon\Mvc\Model\Validator\PresenceOf([
                "field"   => "userName",
                "message" => "用户名不能为空",
            ]));
        $this->validate(new Email([
            "field"   => "emai",
            "message" => "请输入正确的邮箱",
        ]));
        return $this->validationHasFailed() != true;
    }

    /**
     * 验证
     * //     */
    //    public function validation(){
    //
    //        $this->validate(new \Phalcon\Mvc\Model\Validator\PresenceOf(
    //            array(
    //                "field"   => "password",
    //                "message" => "密码不能为空",
    //            )
    //        ));
    //        return $this->validationHasFailed() != true;
    //
    //    }
}
